package com.welinkcredit.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.text.ParseException;  

import javax.servlet.http.HttpServletRequest;
/**
 * 公共工具
 * @author Administrator
 */
public class CommonUtil {
	
	//日期转字符串
	public static String Date2String(Date date){
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
		String dateStr=sdf.format(date);
		return dateStr;
	}
	
	public static void main(String[] args) throws ParseException {
		//System.out.println(Date2String(new Date()));
		//String address = getAddressByIP("169.254.62.142");
		//System.out.println(address);
		
		 	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
	        Date d1=sdf.parse("2017-04-08");  
	        Date d2= new Date();
	        System.out.println(">>>>>>:"+daysBetween(d1,d2));  
	        //System.out.println(daysBetween("2012-08-08","2012-09-10")); 
	}
	
	/**
	 * 获取随机验证码
	 * @param charCount
	 * @return
	 */
	public static String getRandNum(int charCount) {
        String charValue = "";
        for (int i = 0; i < charCount; i++) {
            char c = (char) (randomInt(0, 10) + '0');
            charValue += String.valueOf(c);
        }
        return charValue;
    }
	public static int randomInt(int from, int to) {
	    Random r = new Random();
	    return from + r.nextInt(to - from);
	}
	
	public static String getAddressByIP(String strIP){ 
	  
	  String resultAddress = "未知";
	  try
	  {
	    URL url = new URL( "http://ip.qq.com/cgi-bin/searchip?searchip1=" + strIP); 
	    URLConnection conn = url.openConnection(); 
	    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"GBK")); 
	    String line = null; 
	    StringBuffer result = new StringBuffer(); 
	    while((line = reader.readLine()) != null)
	    { 
	      result.append(line); 
	    } 
	    reader.close(); 
	    try{
	    	strIP = result.substring(result.indexOf( "该IP所在地为：" ));
		    strIP = strIP.substring(strIP.indexOf( "：") + 1);
		    String province = strIP.substring(6, strIP.indexOf("省"));
		    String city = strIP.substring(strIP.indexOf("省") + 1, strIP.indexOf("市"));
		    resultAddress = province+city;
		    if(resultAddress!=null && resultAddress.length()>64){
		    	resultAddress = "未知";
		    }
		    //System.out.println("=========================>>>resultAddress:"+resultAddress);
	    }catch(Exception e){
	    	resultAddress = "未知";
	    }
	    //System.out.println("================>>>:"+resultAddress);
	  }catch( IOException e){ 
		resultAddress = "未知";
	    e.printStackTrace();
	  }
	  return resultAddress;
	}
	
	public static String getIpAddr(HttpServletRequest request) {     
	      String ip = request.getHeader("x-forwarded-for");     
	      if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {     
	         ip = request.getHeader("Proxy-Client-IP");     
	     }     
	      if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {     
	         ip = request.getHeader("WL-Proxy-Client-IP");     
	      }     
	     if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {     
	          ip = request.getRemoteAddr();     
	     }     
	     return ip;     
	}   
	
	
	
	public static String getRandomLetter(){   
        String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";   
        char[] c = s.toCharArray();   
        Random random = new Random();   
        return c[random.nextInt(c.length)]+"";
    }  
	
	/**  
     * 计算两个日期之间相差的天数  
     * @param smdate 较小的时间 
     * @param bdate  较大的时间 
     * @return 相差天数 
     * @throws ParseException  
     */    
    public static int daysBetween(Date smdate,Date bdate) throws ParseException    
    {    
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
        smdate=sdf.parse(sdf.format(smdate));  
        bdate=sdf.parse(sdf.format(bdate));  
        Calendar cal = Calendar.getInstance();    
        cal.setTime(smdate);    
        long time1 = cal.getTimeInMillis();                 
        cal.setTime(bdate);    
        long time2 = cal.getTimeInMillis();         
        long between_days=(time2-time1)/(1000*3600*24);  
            
       return Integer.parseInt(String.valueOf(between_days))+1;//计算利息，统一加1           
    }    
      
	/** 
	*字符串的日期格式的计算 
	*/  
    public static int daysBetween(String smdate,String bdate) throws ParseException{  
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
        Calendar cal = Calendar.getInstance();    
        cal.setTime(sdf.parse(smdate));    
        long time1 = cal.getTimeInMillis();                 
        cal.setTime(sdf.parse(bdate));    
        long time2 = cal.getTimeInMillis();         
        long between_days=(time2-time1)/(1000*3600*24);  
            
       return Integer.parseInt(String.valueOf(between_days));     
    }  

    /**
     * 
     * @param param
     * @return
     */
    public static BigDecimal double2BigDecimal(float param){
    	
    	DecimalFormat myformat=new java.text.DecimalFormat("0.00");
		String paramStr = myformat.format(param);  
    	BigDecimal decimal = new BigDecimal(paramStr);
    	return decimal;
    } 
}
